import React, { useState, useEffect, useContext } from 'react';
import {
  FlatList, RefreshControl, SafeAreaView
} from 'react-native';
import { Tip } from 'beeshell';
import { observer } from 'mobx-react-lite';
import { colors } from '../../constants/theme';
import { MessageItem } from '../../components';
import Http from '../../service/http';
import requestCheck from '../../utils/RequestCheckUtil';

import MessageStore from '../../store/messageStore';

const renderItem = (item, type, refresh, setRefresh) => (
  <MessageItem
    item={item}
    type={type}
    refresh={refresh}
    setRefresh={setRefresh}
  />
);

// type
function MessageList({ type, navigation }) {
  const [dataSource, setDataSource] = useState([]);
  // const [refresh, setRefresh] = useState(0);
  const { refresh, setRefresh } = useContext(MessageStore);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const didFocusListener = navigation.addListener(
      'didFocus',
      () => { setRefresh(); },
    );
    return () => didFocusListener.remove();
  }, [navigation, refresh, setRefresh, type]);

  useEffect(() => {
    async function fetchData() {
      switch (type) {
        case 'unread': {
          const res = await Http.getUnreadMessage();
          const callback = ({ unread }) => {
            setDataSource(unread);
          };
          requestCheck(res, callback, navigation);
          setIsLoading(false);
          break;
        }
        case 'read': {
          const res = await Http.getReadMessage();
          const callback = ({ read }) => {
            setDataSource(read);
          };
          requestCheck(res, callback, navigation);
          setIsLoading(false);
          break;
        }
        case 'sent': {
          const res = await Http.getSentMessage();
          const callback = ({ sent }) => {
            setDataSource(sent);
          };
          requestCheck(res, callback, navigation);
          setIsLoading(false);
          break;
        }
        default: {
          Tip.show('参数错误');
        }
      }
    }
    fetchData();
  }, [navigation, type, refresh]);

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        data={dataSource}
        renderItem={(item) => renderItem(item.item, type, refresh, setRefresh)}
        keyExtractor={(item) => `${item.messageId}`}
        refreshControl={(
          <RefreshControl
            title="加载中"
            titleColor={colors.secondary}
            colors={[colors.primary, colors.secondary]}
            tintColor={colors.primary}
            refreshing={isLoading}
            onRefresh={() => setRefresh(refresh + 1)}
          />
        )}
      />
    </SafeAreaView>
  );
}

export default observer(MessageList);
